<?php

namespace App\Http\Controllers;

use App\Categories;
use Illuminate\Http\Request;

class CategoriesController extends Controller
{
    public function index(){
//        return json_encode(['status'=>'ok xj']);

        $categories = Categories::all();
        if (empty($categories)){
            return json_encode(['status'=>'empty']);
        }
        $caties = [];
        foreach($categories as $cate){
            $caties[$cate['cate_id']] = $cate['cate_name'];
        }
        return json_encode(['status'=>'ok','data'=>$caties]);
    }

    public function imgUpload(Request $request){
//        return ['status'=>'ok xj111','data'=>$request->all()];
        if($request->hasFile('file')){
            $extension = $request->file('file')->extension();

            if(!in_array($extension, array('png', 'gif', 'jpeg', 'jpg'))){
                return json_encode(['status'=>false,'msg'=>'exename error']);
            }

            $path = $request->file('file')->store('img');
            if($path){
                return json_encode(['status'=>'ok','path'=>asset('storage/'.$path)]);
            }else{
                return json_encode(['status'=>0,'msg'=>'upload error']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'upload error']);
        }
    }
}
